const request = require('request');
const md5 = require('md5');
const xml2js = require('xml2js');
const xmlparser = new xml2js.Parser({ explicitArray: false });
var crypto=require('crypto')

var requestPost = function (url, data) {
  return new Promise(function (resolve, reject) {
    request.post({ url: url, body: data }, function (error, response, body) {
      if (error) return reject(error);
      resolve(body);
    })
  })
}

var SandBox_Url = 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey'
var MicroPay_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/micropay"
var UnifiedOrder_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder"
var OrderQuery_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery"
var ReFund_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/refund"
var RefundQuery_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/refundquery"
var DownloadBill_Url = "https://api.mch.weixin.qq.com/sandboxnew/pay/downloadbill"
var nonce_str = "5H16CQ2502SI8ZNMTM67VS"
var appid = "wx0b94b57d8bf359a9"

async function get_sign_key(mch_id, key) {
var sign = md5(`mch_id=${mch_id}&nonce_str=${nonce_str}&key=${key}`).toUpperCase()
  console.log("明文--"+`mch_id=${mch_id}&nonce_str=${nonce_str}&key=${key}`)
  console.log("sign"+sign)
  var template = `<xml><mch_id><![CDATA[${mch_id}]]></mch_id><nonce_str><![CDATA[${nonce_str}]]></nonce_str><sign><![CDATA[${sign}]]></sign></xml>`
  var result = await requestPost(SandBox_Url, template)
  var xmlJSON = await xmlparser.parseStringPromise(result);
  return xmlJSON.xml
}

async function json2xml(params, wxpay_key) {
  const _params = {};
  Object.keys(params).sort().forEach(function (key) { _params[key] = params[key]; });

  var encrypted_str = ``
  var xml = `<xml>`
  for (var key in _params) {
    xml += `<${key}><![CDATA[${_params[key]}]]></${key}>`
    encrypted_str += `${key}=${_params[key]}&`
  }
  encrypted_str += `key=${wxpay_key}`
  encrypted_str = md5(encrypted_str).toUpperCase()

  xml += `<sign><![CDATA[${encrypted_str}]]></sign></xml>`
  return xml
}

async function get_out_trade_no() {
  var num = '';
  for (var i = 0; i < 5; i++) {
    num += Math.floor(Math.random() * 10);
  }
  return `${Date.parse(new Date())}${num}`;
}

async function upgrade(mch_id, key) {
  var wxpay_key = await get_sign_key(mch_id, key)
    console.log("33"+JSON.stringify(wxpay_key))

  if (wxpay_key.sandbox_signkey) {
    console.log("3333")
    wxpay_key = wxpay_key.sandbox_signkey
  }
  else {
    return wxpay_key
  }

  var out_trade_no, out_trade_no_2nd, template, result, xmlJSON

  console.log(`========用例编号1001刷卡========`)
  out_trade_no = await get_out_trade_no()
  var MicroPay_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'body': "check",
    'out_trade_no': out_trade_no,
    'total_fee': "501",
    'spbill_create_ip': "8.8.8.8",
    'auth_code': "120061098828009406",
  }
  template = await json2xml(MicroPay_param, wxpay_key);
  result = await requestPost(MicroPay_Url, template)

  console.log(`========用例编号1001刷卡正常支付查询========`)
  var OrderQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no,
  }
  template = await json2xml(OrderQuery_param, wxpay_key);
  result = await requestPost(OrderQuery_Url, template)

  console.log(`========用例编号1002刷卡========`)
  out_trade_no_2nd = await get_out_trade_no()
  MicroPay_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'body': "check",
    'out_trade_no': out_trade_no_2nd,
    'total_fee': "502",
    'spbill_create_ip': "8.8.8.8",
    'auth_code': "120061098828009406",
  }
  template = await json2xml(MicroPay_param, wxpay_key);
  result = await requestPost(MicroPay_Url, template)

  console.log(`========用例编号1002刷卡正常支付查询========`)
  OrderQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(OrderQuery_param, wxpay_key);
  result = await requestPost(OrderQuery_Url, template)

  console.log(`========用例编号1002刷卡支付退款========`)
  var ReFund_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_refund_no': out_trade_no,
    'total_fee': "502",
    'refund_fee': "501",
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(ReFund_param, wxpay_key);
  result = await requestPost(ReFund_Url, template)

  console.log(`========用例编号1002刷卡支付退款查询========`)
  var RefundQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(RefundQuery_param, wxpay_key);
  result = await requestPost(RefundQuery_Url, template)


  console.log(`========用例编号1003-公众号/APP/扫码正常支付========`)
  out_trade_no = await get_out_trade_no()
  var UnifiedOrder_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'body': "check",
    'out_trade_no': out_trade_no,
    'total_fee': "551",
    'notify_url': "https://www.weixin.qq.com/wxpay/pay.php",
    'spbill_create_ip': "8.8.8.8",
    'trade_type': "JSAPI",
  }
  template = await json2xml(UnifiedOrder_param, wxpay_key);
  result = await requestPost(UnifiedOrder_Url, template)

  console.log(`========用例编号1003-公众号/APP/扫码正常支付查询========`)
  OrderQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no,
  }

  template = await json2xml(OrderQuery_param, wxpay_key);
  result = await requestPost(OrderQuery_Url, template)

  console.log(`========用例编号1004-公众号/APP/扫码支付退款========`)
  out_trade_no_2nd = await get_out_trade_no()
  UnifiedOrder_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'body': "check",
    'out_trade_no': out_trade_no_2nd,
    'total_fee': "552",
    'notify_url': "https://www.weixin.qq.com/wxpay/pay.php",
    'spbill_create_ip': "8.8.8.8",
    'trade_type': "JSAPI",
  }
  template = await json2xml(UnifiedOrder_param, wxpay_key);
  result = await requestPost(UnifiedOrder_Url, template)

  console.log(`========用例编号1004-公众号/APP/扫码支付退款查询========`)
  OrderQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(OrderQuery_param, wxpay_key);
  result = await requestPost(OrderQuery_Url, template)

  console.log(`========用例编号1004-公众号/APP/扫码支付退款========`)
  ReFund_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_refund_no': out_trade_no,
    'total_fee': "552",
    'refund_fee': "551",
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(ReFund_param, wxpay_key);
  result = await requestPost(ReFund_Url, template)

  console.log(`========用例编号1004-公众号/APP/扫码支付退款查询========`)
  RefundQuery_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'out_trade_no': out_trade_no_2nd,
  }
  template = await json2xml(RefundQuery_param, wxpay_key);
  result = await requestPost(RefundQuery_Url, template)

  console.log(`========下载交易的对账单========`)
  var DownloadBill_param = {
    'appid': 'wx0b94b57d8bf359a9',
    'mch_id': mch_id,
    'nonce_str': nonce_str,
    'bill_date': "2021-04-01",
    'bill_type': "ALL"
  }
  template = await json2xml(DownloadBill_param, wxpay_key);
  await requestPost(DownloadBill_Url, template)

  return { retcode: 0 }
}

async function tttt(){

 var xx= await upgrade('1609180817','2323sadasdasfasfwe21321313213212');
} 

tttt()